<template>
  <view class="container">
    <view class="header">您好，欢迎登录！</view>

    <view class="login-type-switch">
      <view class="switch-container">
        <view
          :class="['switch-option', loginForm.role === 'USER' ? 'active' : '']"
          @tap="switchRole('USER')"
        >
          用户登录
        </view>
        <view
          :class="['switch-option', loginForm.role === 'EMPLOY' ? 'active' : '']"
          @tap="switchRole('EMPLOY')"
        >
          企业登录
        </view>
      </view>
    </view>
	
    <view class="form">
      <view class="input-group">
        <text class="label">{{ loginForm.role === 'USER' ? '邮箱' : '企业邮箱' }}</text>
        <input
          type="text"
          v-model="loginForm.email"
          :placeholder="loginForm.role === 'USER' ? '请输入邮箱' : '请输入企业邮箱'"
          @blur="validateEmail"
        />
        <text class="error-message" v-if="errors.email">{{ errors.email }}</text>
      </view>

      <view class="input-group">
        <text class="label">{{ loginForm.role === 'USER' ? '密码' : '密码' }}</text>
        <input
          type="password"
          v-model="loginForm.password"
          :placeholder="loginForm.role === 'USER' ? '请输入密码' : '请输入密码'"
          @blur="validatePassword"
        />
        <text class="error-message" v-if="errors.password">{{ errors.password }}</text>
      </view>
    </view>

    <button class="login-btn" @tap="handleLogin">登录</button>

    <view class="ques">
      <view @tap="goForgot">忘记密码</view>
      <view class="divider">|</view>
      <view @tap="goRegister" class="register-link">去注册</view>
    </view>

    <view class="footer">
      登录即表明同意隐私协议和用户服务协议
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      loginForm: {
        role: 'USER',
        email: '',
        password: ''
      },
      errors: {
        email: '',
        password: ''
      }
    };
  },
  methods: {
    ...mapActions(['passwordLogin']),   
    switchRole(role) {
      this.loginForm.role = role;
      this.clearErrors();
      this.loginForm.email = '';
      this.loginForm.password = '';
    },
    validateEmail() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!this.loginForm.email) {
        this.errors.email = '请输入邮箱';
        return false;
      } else if (!emailRegex.test(this.loginForm.email)) {
        this.errors.email = '邮箱格式不正确';
        return false;
      } else {
        this.errors.email = '';
        return true;
      }
    },
    validatePassword() {
      if (!this.loginForm.password) {
        this.errors.password = '请输入密码';
        return false;
      } else if (this.loginForm.password.length < 6) {
        this.errors.password = '密码长度至少6位';
        return false;
      } else {
        this.errors.password = '';
        return true;
      }
    },
    async handleLogin() {
      const isEmailValid = this.validateEmail();
      const isPasswordValid = this.validatePassword();

      if (isEmailValid && isPasswordValid) {
        try {
          await this.passwordLogin({
            email: this.loginForm.email,
            password: this.loginForm.password,
            role: this.loginForm.role
          })
          uni.showToast({
            title: `${this.loginForm.role === 'USER' ? '用户' : '企业'}登录成功`,
            icon: 'success'
          });
          
          // 确保设置showTabBar为true
          this.$store.commit('SET_SHOW_TAB_BAR', true);
          console.log('登录成功后showTabBar状态:', this.$store.state.showTabBar);
          console.log('登录成功后role状态:', this.$store.state.role);
          
          // 延迟一点时间再跳转，确保状态已更新
          setTimeout(() => {
            try {
              // 直接使用reLaunch代替switchTab，避免tabBar问题
             uni.switchTab({ 
  url: '/pages/index/index',
  success: () => {
    console.log('switchTab成功');
  },
  fail: (err) => {
    console.error('switchTab失败:', err);
    // 如果switchTab失败，可以考虑使用reLaunch作为备选方案
    uni.reLaunch({ url: '/pages/index/index' });
  }
});
            } catch (e) {
              console.error('导航异常:', e);
              uni.reLaunch({ url: '/pages/index/index' });
            }
          }, 500);
        } catch (error) {
          const errorMsg = error && error.message 
                  ? error.message 
                  : '登录失败，请重试';
                
                uni.showToast({
                  title: errorMsg,
                  icon: 'none'
                });
        }
      }
    },
    clearErrors() {
      this.errors.email = '';
      this.errors.password = '';
    },
    goRegister() {
      uni.navigateTo({ url: '/pages/register/register-index/register-index' });
    },
    goForgot() {
      uni.navigateTo({ url: '/pages/forgot/forgot-index/forgot-index' });
    }
  }
};
</script>

<style scoped>
.container {
  margin: 100rpx;
}

.header {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 60rpx;
  text-align: center;
  margin-top: 15rpx;
}

.login-type-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.switch-container {
  display: flex;
  width: 400rpx;
  height: 70rpx;
  position: relative;
}

.switch-option {
  flex: 1;
  text-align: center;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.switch-option.active {
  color: #b6ccd8;
  font-weight: bold;
}

.switch-option.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 4rpx;
  background-color: #b6ccd8;
  border-radius: 2rpx;
}

.type-btn {
  padding: 10rpx 30rpx;
  margin: 0 10rpx;
  font-size: 28rpx;
  color: #999;
  border: 2rpx solid #ccc;
  border-radius: 30rpx;
}

.type-btn.active {
  color: #fff;
  background-color: #b6ccd8;
  border-color: #b6ccd8;
}

.input-group {
  margin-bottom: 40rpx;
  position: relative;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #000;
  margin-bottom: 20rpx;
}

input {
  width: 100%;
  padding: 20rpx 0;
  border: none;
  font-size: 32rpx;
  outline: none;
  background: transparent;
  border-bottom: 2rpx solid #ccc;
}

.error-message {
  position: absolute;
  bottom: -35rpx;
  left: 0;
  font-size: 24rpx;
  color: #ff4d4f;
}

.login-btn {
  width: 100%;
  margin-bottom: 30rpx;
  padding: 20rpx;
  font-size: 32rpx;
  color: #fff;
  background-color: #b6ccd8;
  border-radius: 70rpx;
  border: 2rpx solid #1d1c1c;
}

.ques {
  font-size: 24rpx;
  color: #999;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
}

.divider {
  margin: 0 10rpx;
}

.footer {
  margin-top: 60rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center;
}
</style>